package servlet.user;

import entity.Comment;
import entity.Pet;
import entity.User;

import service.CommentService;
import service.PetService;

import service.Impl.CommentServiceImpl;
import service.Impl.PetServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Date;
import java.time.LocalDate;

@WebServlet(urlPatterns = "/user/commentAdd")
public class CommentAddServlet extends HttpServlet {
    private CommentService commentService = new CommentServiceImpl();
    private PetService petService = new PetServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求编码
        req.setCharacterEncoding("UTF-8");

        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        String formattedDate = currentDate.toString(); // 格式为 yyyy-MM-dd

        // 获取所有宠物
        req.setAttribute("pet", petService.findAll());

        // 设置当前日期到请求属性
        req.setAttribute("currentDate", formattedDate);

        // 转发到添加评论页面
        req.getRequestDispatcher("/user/cmad.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求编码
        req.setCharacterEncoding("UTF-8");

        // 获取当前会话
        HttpSession session = req.getSession();

        // 获取用户信息（假设用户信息存储在会话中）
        User user = (User) session.getAttribute("user");
        if (user == null) {
            // 如果用户未登录，重定向到登录页面
            resp.sendRedirect(req.getContextPath() + "/user/index");
            return;
        }

        // 获取表单参数
        int userId = user.getId(); // 从会话中获取用户ID
        int petId = Integer.parseInt(req.getParameter("pet"));
        String commentText = req.getParameter("comment");
        String commentTimeStr = req.getParameter("commentTime");

        // 创建 Comment 对象
        Comment comment = new Comment();
        User userObj = new User();
        userObj.setId(userId); // 设置用户ID
        comment.setUser(userObj);

        Pet pet = new Pet();
        pet.setId(petId);
        comment.setPet(pet);

        // 设置评论内容
        comment.setContent(commentText);

        // 设置评论时间
        comment.setCommentTime(Date.valueOf(commentTimeStr));

        // 保存到数据库
        commentService.addComment(comment);

        // 重定向到评论列表页面或其他页面
        resp.sendRedirect(req.getContextPath() + "/user/comment");
    }
}
